package hash;

import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

/**
 * Created with IntelliJ IDEA.
 * Description: 349.两个数组的交集
 * User: Li_yizYa
 * Date: 2025—03—26
 * Time: 21:55
 */
public class Solution2 {
    public static void main(String[] args) {
        int[] nums1 = {9, 4, 9, 8, 4};
        int[] nums2 = {4, 9, 5};
        int[] ret = intersection(nums1, nums2);
        for (int i : ret) {
            System.out.print(i + " ");
        }
    }
    private static int[] intersection(int[] nums1, int[] nums2) {
        if (nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0) {
            return new int[0];
        }
        int[] hash1 = new int[1002];
        int[] hash2 = new int[1002];
        for (int i : nums1) {
            hash1[i]++;
        }

        for (int i : nums2) {
            hash2[i]++;
        }
        List<Integer> retList = new LinkedList<>();
        for (int i = 0; i < 1002; i++) {
            if (hash1[i] > 0 && hash2[i] > 0) {
                retList.add(i);
            }
        }
        int index = 0;
        int[] ret = new int[retList.size()];
        for (int i : retList) {
            ret[index++] = i;
        }
        return ret;
    }
    /**
     * HashSet
     * @param nums1
     * @param nums2
     * @return
     */
    private static int[] intersection1(int[] nums1, int[] nums2) {
        if (nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0) {
            return new int[0];
        }
        Set<Integer> set = new HashSet<>();
        Set<Integer> retSet = new HashSet<>();
        //遍历数组nums1，并将元素加入set1中
        for (int i : nums1) {
            set.add(i);
        }
        //遍历数组nums2，判断元素是否存在于nums1中
        for (int i : nums2) {
            if (set.contains(i)) {
                retSet.add(i);
            }
        }
        int[] ret = new int[retSet.size()];
        int index = 0;
        //将retSet中数据写入ret中
        for (int i : retSet) {
            ret[index++] = i;
        }
        return ret;
    }
}
